﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Collections.Generic;

using Progresoft.Scheduler.RemoteInterface;
using Progresoft.Scheduler.RemoteInterface.Api;
using Progresoft.Common;
using Progresoft.Common.LanguageTools;

public partial class Dashboard : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			Connector connector = ConnectorManager.GetConnector();
			DashboardData data = connector.GetDashboard();
			rptScheduledTasks.DataSource = data.ScheduledTasks;
			rptPeriodicTasks.DataSource = data.PeriodicTasks;
			this.DataBind();
		}
	}

	/// <summary>
	/// CSS для строки задач по расписанию.
	/// </summary>
	protected string GetScheduledTaskRowCss(ScheduledTaskStatus status)
	{
		switch (status)
		{
			case ScheduledTaskStatus.Unknown:
				return "schedulerTableGray";
			case ScheduledTaskStatus.Failed:
			case ScheduledTaskStatus.Cancelled:
				return "schedulerTableRed";
			default:
				return string.Empty;
		}
	}

	/// <summary>
	/// CSS для строки периодической задачи.
	/// </summary>
	protected string GetPeriodicTaskRowCss(PeriodicTaskStatus status)
	{
		switch (status)
		{
			case PeriodicTaskStatus.Unknown:
			case PeriodicTaskStatus.Disabled:
				return "schedulerTableGray";
			case PeriodicTaskStatus.Failed:
				return "schedulerTableRed";
			default:
				return string.Empty;
		}
	}

	/// <summary>
	/// Иконка для строки задач по расписанию
	/// </summary>
	protected string GetScheduledTaskStatusIcon(ScheduledTaskStatus status)
	{
		return string.Format("~/Images/scheduler/status_{0}.gif", status.ToString().ToLower());
	}

	/// <summary>
	/// Иконка для строки задач по расписанию
	/// </summary>
	protected string GetPeriodicTaskStatusIcon(PeriodicTaskStatus status)
	{
		switch (status)
		{
			case PeriodicTaskStatus.Disabled:
				return "~/Images/scheduler/status_unknown.gif";
			default:
				return string.Format("~/Images/scheduler/status_{0}.gif", status.ToString().ToLower());
		}
	}

	/// <summary>
	/// Тултип для статуса задачи по расписанию
	/// </summary>
	protected string GetScheduledTaskStatusTooltip(ScheduledTaskStatus status)
	{
		return EnumHelper.GetValueName<ScheduledTaskStatus>(status);
	}
	
	/// <summary>
	/// Период запуска задачи
	/// </summary>
	protected string FormatPeriod(TimeSpan period)
	{
		string result = string.Empty;
		
		int days = period.Days;
		if (days > 0)
			result += string.Format("{0} {1}", days, Decliner.Instance.Coordinate(days, "день"));
		
		int hours = period.Hours;
		if (hours > 0)
			result += string.Format(" {0} {1}", hours, Decliner.Instance.Coordinate(hours, "час"));
		
		int minutes = period.Minutes;
		if (minutes > 0)
			result += string.Format(" {0} {1}", minutes, Decliner.Instance.Coordinate(minutes, "минута"));

		int seconds = period.Seconds;
		if (seconds > 0)
			result += string.Format(" {0} {1}", seconds, Decliner.Instance.Coordinate(seconds, "секунда"));

		return result;
	}

	/// <summary>
	/// Получить строку со временем последнего запуска
	/// </summary>
	protected string FormatLastStart(DateTime? time)
	{
		return time.HasValue ?
			time.Value.ToString("G")
			: "не запускалась";
	}

	/// <summary>
	/// Получить строку с датой последнего успешного завершения
	/// </summary>
	protected string FormatLastSuccessfull(DateTime? time)
	{
		return time.HasValue ?
			time.Value.ToString("G")
			: "&ndash;";
	}

	protected void rptScheduledTasks_ItemCommand(object source, ListViewCommandEventArgs e)
	{
		string[] arguments = e.CommandArgument.ToString().Split(',');
        string task = arguments[0];
        string system = arguments[1];

		string serverUrl = ConnectorManager.GetServerUrl(system);
		Connector connector = ConnectorManager.GetConnector();
		SchedulerServer server = connector.GetServer(serverUrl);

		switch (e.CommandName)
		{
			case ("StartTask"):;
				server.StartTask(system, task, "DashBoard");
				break;
			
			case ("StopTask"):
				server.StopTask(system, task);
				break;
		}

		Response.Redirect("~/Dashboard.aspx");
	}
}
